﻿package net.wangit.framework.validation;

import java.util.HashMap;
import java.util.Map;

import net.wangit.MapList;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.context.ActionResult;
import net.wangit.framework.session.AgileSession;


public class ValidationResult {

	private boolean pass;
	private Map invalidFields;
	private ActionContext ac;
	private ActionResult ar;
	private boolean mark;
	private String unitId;
	private MapList unitInvalidFields;

	public ValidationResult(ActionContext ac, boolean mark) {
		pass = true;
		invalidFields = new HashMap();
		unitId = null;
		this.mark = mark;
		this.ac = ac;
		ar = ac.getActionResult();
	}

	public boolean pass() {
		return pass;
	}

	public void setUnitId(String unitId) {
		finishLastUnit();
		this.unitId = unitId;
		unitInvalidFields = new MapList();
	}

	public void addError(String error) {
		ar.addError(error);
		pass = false;
	}

	public void addError(int rowIndex, String id, String error) {
		addError(error);
		if (mark)
			unitInvalidFields.put(rowIndex, id, "");
	}

	public void finish() {
		if (mark) {
			finishLastUnit();
			AgileSession session = ActionContextHelper.getSession(ac);
			session.setInvalidFields(invalidFields);
		}
	}

	private void finishLastUnit() {
		if (mark && unitId != null && unitInvalidFields.size() > 0)
			invalidFields.put(unitId, unitInvalidFields);
	}
}
